package dk.hewison.client.data;

import com.google.gwt.user.client.rpc.AsyncCallback;
import dk.hewison.client.Log;
import dk.hewison.client.data.request.MyRequestBuilder;
import dk.hewison.client.domain.Directory;

import java.util.HashMap;

/**
 * Client side cache.
 *
 * @author John Hewison
 * @author $LastChangedBy: john.hewison $:  $ $LastChangedDate: 2009-02-15 12:47:07 +0000 (Sun, 15 Feb 2009) $:
 * @version $Revision: 364 $:
 */
public class DataController implements MediaServerAsync {

    private MediaServerAsync mediaServerAsync;

    private HashMap<String, Directory> directoryHashMap = new HashMap<String, Directory>();


    public void getDirectory(final Directory directory, final AsyncCallback<Directory> aCallback) {
        //is it cached
        if (directory != null && directoryHashMap.containsKey(directory.getAbsolutePath())) {
            Log.debug("get from cache " + directory);
            aCallback.onSuccess(directoryHashMap.get(directory.getAbsolutePath()));
        } else {
            Log.debug("retrieve from server " + directory);
            Callback<Directory> callback = new Callback<Directory>() {
                @Override
                public void doSuccess(Directory result) {
                    completeDirectoryInfo(result);
                    aCallback.onSuccess(result);
                }
            };
            mediaServerAsync.getDirectory(directory, callback);
        }
    }

    /**
     * set the absolute path for the directory.
     *
     * @param directory the Directory just retrieved from the server.
     */
    private void completeDirectoryInfo(Directory directory) {
        directoryHashMap.put(directory.getAbsolutePath(), directory);
    }

    public void getDirectoryImageNames(Directory directory, AsyncCallback<Directory> asyncCallback) {
        if (directory.isLoaded()) {
            asyncCallback.onSuccess(directory);
            return;
        }
        mediaServerAsync.getDirectoryImageNames(directory, asyncCallback);
    }


    private static DataController instance;

    private DataController() {
        mediaServerAsync = new MyRequestBuilder();
    }

    public static DataController getInstance() {
        if (instance == null) {
            instance = new DataController();
        }
        return instance;
    }


}
